package org.example.system.interceptor;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.Employee;
import org.example.system.service.EmployeeService;
import org.example.utils.JwtUtil;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问此拦截器前，token验证已通过
 * 在访问接口之前拦截，判断用户权限是否满足要求
 */
@Component
@Slf4j
public class RoleInterceptor implements HandlerInterceptor {

    @Autowired
    private EmployeeService employeeService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer","").trim();
        String payload = JwtUtil.get(token);
        Long id = Long.parseLong(payload.split(",") [0]); //通过token获取员工id
        Employee employee = employeeService.getOne(id);
        String role = employee.getRole();
        log.info("--------------RoleInterceptor | preHandle | role：{}",role);
        //如果用户为审核 或者 管理员访问delete接口时不放行
        if(request.getRequestURL().indexOf("delete") >= 0 && (role.equals("审核")  || role.equals("管理员"))){
            String result = JSON.toJSONString(R.fail(403,"员工权限不足"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(result);
            response.getWriter().flush();
            return false;
        }

        return true;
    }
}
